package lc20240619;

public class FindPeakMax {
    public int findPeakElement(int[] nums) {
        if (nums == null || nums.length == 0) {
            return -1; // 数组为空时返回-1表示错误
        }

        int left = 0;
        int right = nums.length - 1;

        //采用二分查找的算法。
        while (left < right) {
            int mid = left + (right - left) / 2;

            // 比较中间元素与其右侧元素
            if (nums[mid] < nums[mid + 1]) {
                // 如果中间元素小于右侧元素，峰值在右侧
                left = mid + 1;
            } else {
                // 如果中间元素大于右侧元素，峰值在左侧或中间元素
                right = mid;
            }
        }

        // 返回峰值元素的索引
        return left;
    }

    public static void main(String[] args) {
        FindPeakMax solution = new FindPeakMax();
        int[] nums = {1, 2, 3, 1};
        int peakIndex = solution.findPeakElement(nums);
        System.out.println("The peak element index is: " + peakIndex);
    }
}
